import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AsyncComposeDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 异步任务1
        CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("执行任务1...");
            sleep(1000);
            return "任务1完成";
        });

        // 异步任务2
        CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("执行任务2...");
            sleep(2000);
            return "任务2完成";
        });

        // 异步任务3
        CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("执行任务3...");
            sleep(1500);
            return "任务3完成";
        });

        // 等待任务1、2、3全部完成后，再执行任务4
        CompletableFuture<Void> allTasks = CompletableFuture.allOf(task1, task2, task3);

        CompletableFuture<String> task4 = allTasks.thenApply(v -> {
            try {
                String r1 = task1.get();
                String r2 = task2.get();
                String r3 = task3.get();
                System.out.println("前面三个任务结果: " + r1 + " | " + r2 + " | " + r3);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("执行任务4...");
            return "任务4完成";
        });

        // 获取最终结果
        System.out.println("最终结果: " + task4.get());
        CompletableFuture<Integer> task5 = CompletableFuture.supplyAsync(()->4).thenApply(r->r*5).thenApply(r->r+3);
        System.out.println(task5.join());
    }

    private static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException ignored) {}
    }
}
